<script setup>
import { onMounted, ref } from 'vue'
import { faker } from '@faker-js/faker'
import {Plus} from "@element-plus/icons-vue";
import {ElMessage, ElNotification} from "element-plus";
import {BaseURL} from "@/utils/request.js";
import {getUser, updateUser} from "@/store/userStore.js";
import {updateUserFetch} from "@/api/user.js";

const formData = ref({});
const uploadUrl = ref(BaseURL + '/upload');

// 开发环境初始化模拟数据
onMounted(() => {
  formData.value = getUser().userInfo;
})

const handleAvatarSuccess = (response) => {
  if (response) {
    console.log(response);
    formData.value.avatar = response.data;
    console.log(formData.value.avatar);
    ElNotification({
      title: '上传成功',
      message: '图片上传成功',
      type:'success'
    });
  }
};

const handleAvatarError = (error) => {
  console.log(error);
  ElNotification({
    title: '上传失败',
    message: '图片上传失败',
    type: 'error'
  });
}

const beforeAvatarUpload = (rawFile) => {
  const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'];
  if (!allowedTypes.includes(rawFile.type)) {
    ElMessage.error('头像图片必须是 JPG、JPEG、PNG、GIF 格式！')
    return false
  } else if (rawFile.size / 1024 / 1024 > 5) {
    ElMessage.error('头像图片大小不能超过 5MB！')
    return false
  }
  return true
}

const formRules = {
  userRealName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '邮箱格式不正确', trigger: ['blur', 'change'] }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  type: [
    { required: true, message: '请选择用户类型', trigger: 'change' }
  ]
}

const handleSubmit = async () => {
  await updateUserFetch(formData.value);
  await updateUser(formData.value)
  ElMessage({
    message: '修改成功',
    type:'success'
  });
}

</script>

<template>
  <div class="user-info-container">
    <el-card class="info-card">
      <template #header>
        <div class="card-header">
          <h2>个人信息</h2>
          <el-button type="primary" @click="handleSubmit">保存修改</el-button>
        </div>
      </template>

      <el-form :model="formData" :rules="formRules" label-position="top" class="info-form">
        <div class="form-section">
          <div class="section-title">基本信息</div>
          <div class="form-grid">
            <el-form-item label="头像">
              <el-upload
                class="avatar-uploader"
                :action="uploadUrl"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :on-error="handleAvatarError"
                :before-upload="beforeAvatarUpload"
                accept="image/jpeg,image/jpg,image/png,image/gif"
              >
                <div class="avatar-wrapper">
                  <img v-if="formData.avatar" :src="formData.avatar" class="avatar" alt="用户头像"/>
                  <el-icon v-else class="avatar-uploader-icon"><Plus/></el-icon>
                </div>
              </el-upload>
            </el-form-item>

            <div class="form-group">
              <el-form-item label="用户名">
                <el-input v-model="formData.username" readonly />
              </el-form-item>
              <el-form-item label="注册时间">
                <el-input v-model="formData.createTime" readonly />
              </el-form-item>
            </div>
          </div>
        </div>

        <div class="form-section">
          <div class="section-title">详细信息</div>
          <div class="form-grid">
            <el-form-item label="真实姓名" prop="userRealName">
              <el-input v-model="formData.userRealName" placeholder="请输入真实姓名" />
            </el-form-item>

            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="formData.gender">
                <el-radio :label="1">男</el-radio>
                <el-radio :label="2">女</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="邮箱" prop="email">
              <el-input v-model="formData.email" placeholder="请输入邮箱地址" />
            </el-form-item>

            <el-form-item label="手机号" prop="phone">
              <el-input v-model="formData.phone" placeholder="请输入手机号码" />
            </el-form-item>
          </div>
        </div>

        <div class="form-section">
          <div class="section-title">安全设置</div>
          <div class="form-grid">
            <el-form-item label="密码" prop="password">
              <el-input v-model="formData.password" show-password placeholder="不修改请留空" />
            </el-form-item>
          </div>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<style scoped lang="scss">
.user-info-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;

  .info-card {
    max-width: 800px;
    margin: 0 auto;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 20px;

      h2 {
        margin: 0;
        font-size: 20px;
        color: #303133;
        font-weight: 500;
      }
    }

    .info-form {
      padding: 20px;

      .form-section {
        margin-bottom: 30px;

        &:last-child {
          margin-bottom: 0;
        }

        .section-title {
          font-size: 16px;
          color: #303133;
          font-weight: 500;
          margin-bottom: 20px;
          padding-left: 10px;
          border-left: 4px solid var(--el-color-primary);
        }

        .form-grid {
          display: grid;
          grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
          gap: 20px;
        }

        .form-group {
          display: flex;
          flex-direction: column;
          gap: 20px;
        }
      }
    }
  }

  .avatar-uploader {
    text-align: center;
    margin-bottom: 20px;

    .avatar-wrapper {
      width: 120px;
      height: 120px;
      border: 2px dashed var(--el-border-color);
      border-radius: 12px;
      overflow: hidden;
      cursor: pointer;
      transition: all 0.3s;
      margin: 0 auto;
      background-color: #fafafa;

      &:hover {
        border-color: var(--el-color-primary);
        background-color: #f5f7fa;
      }

      .avatar {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }

      .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }

  :deep(.el-form-item) {
    margin-bottom: 20px;

    .el-form-item__label {
      font-weight: 500;
      color: #606266;
    }

    .el-input__wrapper {
      box-shadow: 0 0 0 1px #dcdfe6 inset;
      transition: all 0.3s;

      &:hover {
        box-shadow: 0 0 0 1px var(--el-color-primary) inset;
      }

      &.is-focus {
        box-shadow: 0 0 0 1px var(--el-color-primary) inset;
      }
    }
  }

  :deep(.el-radio-group) {
    display: flex;
    gap: 20px;
  }
}
</style>
